package sdu.ltp.entity;

import java.util.ArrayList;
import java.util.List;

/**
 * 规约化
 * 对解析的祖数据进行规约
 * @author ljh_2015
 *
 */
public class Convention {

    /**
     * 去壳操作
     * 将添加'[]'的数据去掉壳
     */
    public static String decladding(String sample) {
	int len = sample.length();
	return sample.substring(1,len-1);
    }

    /**
     * 加壳 对数据加壳，数据还原
     * @param sample
     * @return
     */
    public static String cladding(String sample) {
	return "["+sample+"]";
    }

    /**
     * 规约分组
     * 根据mapper_rel 进行分组
     * </br>
     * <li> 一组为rel_keys </li>
     * <li> 一组为rel_indexs </li>
     * </br>
     * @param sample
     */
    public static void conv_grouping(String sample,long sentid,ConventionHandle handle) {
	String[] elements = sample.split("_");
	int len = elements.length;
	int[] values = new int[len];
	List<String> array = new ArrayList<>();
	StringBuilder key = new StringBuilder("<");
	StringBuilder valuec = new StringBuilder("<");
	for(int i=0;i<len;i++) {
	    int index = 1;
	    if((index+=array.indexOf(elements[i]))==0) {
		array.add(elements[i]);
		index = array.size();
		if(index!=1) {
		    key.append(",");
		}
		key.append(elements[i]);
	    } 
	    if(i!=0) {
		valuec.append(",");
	    }
	    values[i]=index;
	    valuec.append(index);
	}
	key.append(">");
	valuec.append(">");
	System.out.println(key.toString()+" "+valuec.toString());
	if(handle!=null) {
	    handle.doConvention(sentid,key.toString(), valuec.toString());
	}
    }

    /**
     * </br>
     * 根据key value 还原mapper_rel
     * </br>
     * @param key 
     * @param value 
     * @return
     */
    public static String returnMapperRel(String key,String value) {
	String kgr = decladding(key);
	String vgr = decladding(value);
	String[] values = vgr.split(",");
	String[] keys = kgr.split(",");
	StringBuilder result = new StringBuilder("[");
	for(int i=0;i<values.length;i++) {
	    if(i!=0) {
		result.append("_");
	    }
	    result.append(keys[Integer.parseInt(values[i])-1]);
	}
	result.append("]");
	return result.toString();
    }

}
